package com.originskyseed.platform.log.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.originskyseed.platform.core.base.BasePage;
import com.originskyseed.platform.core.mongodb.api.MongoUtil;
import com.originskyseed.platform.core.tenant.util.TenantCodeUtil;
import com.originskyseed.platform.core.util.bean.PrimaryKeyGeneratorUtil;
import com.originskyseed.platform.log.model.HomePageCache;
import com.originskyseed.platform.log.service.IHomePageCacheService;

/**
 * Service接口实现类（osi_home_page_cache）
 *
 * @author tang
 */
@DubboService
@Component("homePageCacheService")
public class HomePageCacheServiceImpl implements IHomePageCacheService {

	/**
	 * 日志记录表
	 */
	private final static String HOME_PAGE_CACHE = "osi_home_page_cache";

	/**
	 * 插入记录（仅非空值字段）
	 *
	 * @param record
	 * @return
	 * @throws Exception
	 */
	@Override
	public int insertSelective(HomePageCache record) throws Exception {
		String id = PrimaryKeyGeneratorUtil.getInstance().getRandomKey();
		JSONObject jsonObject = new JSONObject();
		// 设置mongodb数据
		jsonObject.put("id", id);
		jsonObject.put("userId", record.getUserId());
		jsonObject.put("content", record.getContent());
		jsonObject.put("createTime", new Date());
		MongoUtil.getInstance().insert(jsonObject, HOME_PAGE_CACHE);
		return 1;
	}

	/**
	 * 插入记录（仅非空值字段）
	 *
	 * @param HomePageCacheLsit
	 * @return
	 * @throws Exception
	 */
	@Override
	public int batchInsertByList(List<HomePageCache> HomePageCacheLsit) throws Exception {
		for (HomePageCache HomePageCache : HomePageCacheLsit) {
			HomePageCache.setId(PrimaryKeyGeneratorUtil.getInstance().getRandomKey());
			HomePageCache.setCreateTime(new Date());
		}
		MongoUtil.getInstance().batchInsertByList(HomePageCacheLsit, HOME_PAGE_CACHE);
		return 1;
	}

	/**
	 * 查询记录
	 *
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@Override
	public HomePageCache selectByPrimaryKey(String id) throws Exception {
		Query query = getQuery(new HashMap() {
			{
				this.put("id", id);
			}
		});
		List<HomePageCache> list = MongoUtil.getInstance().selectListByQuery(query, HomePageCache.class, HOME_PAGE_CACHE);
		if (list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

	/**
	 * 查询列表
	 *
	 * @param record
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<HomePageCache> selectList(HomePageCache record) throws Exception {
		Query query = getQuery(record.toMap());
		List<JSONObject> jsonObjectList = MongoUtil.getInstance().selectListByQuery(query, JSONObject.class, HOME_PAGE_CACHE);
		return getHomePageCacheJSON(jsonObjectList);
	}

	/**
	 * 分页查询列表
	 *
	 * @param params
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@Override
	public BasePage<HomePageCache> selectListByPage(Map<String, Object> params, BasePage<HomePageCache> page) throws Exception {
		Query query = getQuery(params);
		query.with(Sort.by(new Sort.Order(Sort.Direction.DESC, "createTime")));
		List<HomePageCache> jsonObjectList = MongoUtil.getInstance().selectListByPage(query, page, HomePageCache.class, HOME_PAGE_CACHE);
		// 获取总数
		Long totalNum = MongoUtil.getInstance().selectCountByQuery(query, HOME_PAGE_CACHE);
		page.setTotalRecord(Integer.valueOf(String.valueOf(totalNum)));
		page.setResults(jsonObjectList);
		return page;
	}

	@Override
	public Boolean deleteHomePageCache(String day, String tenantCode) throws Exception {
		if (StringUtils.isNotEmpty(tenantCode)) {
			TenantCodeUtil.getInstance().createServerTenantCode(tenantCode);
		}
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		Date date = new Date();
		// 获取60天之前的日期
		Date orderDays = DateUtils.addDays(date, -Integer.valueOf(day));
		String createTime = dateFormat.format(orderDays);
		Query query = getQuery(new HashMap() {
			{
				this.put("startTimeEnd", createTime);
			}
		});
		MongoUtil.getInstance().deleteByQuery(query, HOME_PAGE_CACHE);
		return true;
	}

	@Override
	public Boolean deleteHomePageCache() throws Exception {
		Query query =  new Query();
		MongoUtil.getInstance().deleteByQuery(query, HOME_PAGE_CACHE);
		return true;
	}

	/**
	 * 公共查询条件
	 *
	 * @param params
	 * @return
	 * @throws ParseException
	 */
	private Query getQuery(Map<String, Object> params) throws ParseException {
		Query query = new Query();
		Criteria criteria = new Criteria();
		if (params.get("id") != null) {
			criteria.and("id").is(String.valueOf(params.get("id")));
		}
		if (params.get("userId") != null) {
			criteria.and("userId").is(String.valueOf(params.get("userId")));
		}
		if (params.get("content") != null) {
			criteria.and("content").is(String.valueOf(params.get("content")));
		}

		query.addCriteria(criteria);
		return query;
	}

	private List<HomePageCache> getHomePageCacheJSON(List<JSONObject> list) {
		List<HomePageCache> HomePageCacheList = new ArrayList<>();
		for (JSONObject jsonObject : list) {
			// JSONObject timeObject = JSONObject.parseObject((JSONObject.toJSONString(jsonObject.get("createTime"))));
			// jsonObject.put("createTime", timeObject.get("$numberLong"));
			HomePageCache HomePageCache = JSONObject.parseObject(JSON.toJSONString(jsonObject), HomePageCache.class);
			HomePageCacheList.add(HomePageCache);
		}
		return HomePageCacheList;
	}

}
